import BetterUtilTools from 'better-util-tools';
import $utils from 'src/plugins/utils';
import api from 'src/plugins/http/api';
import mainMixin from 'src/plugins/mixin';
import store from 'src/store';
import { whitePages} from 'src/plugins/http/whitePages';
const UtilTools = new BetterUtilTools();
let requestTask = null;

const http = opt => {
    opt = opt || {};
    opt.timeout = opt.timeout || 1000 * 60;
    opt.data = opt.data || {};
    opt.header = UtilTools.extend(opt.header || {}, {
        'secret': 'zlgb',
        'appkey': 'a33a1726d93a401b812bafff8d5b73c3'
    });
    opt.method = opt.method ? opt.method.toUpperCase() : 'POST';
    return new Promise((resolve, reject) => {
        http.beforeHttp(opt).then(opt => {
            opt.header.loading = opt.header.loading || {};
            if (opt.header.loading.show == undefined) { opt.header.loading.show = true; }
            if (opt.header.loading.show) {
                uni.showLoading({
                    'title': opt.header.loading.title || '拼命加载中...',
                    'mask': opt.header.loading.mask || true
                });
            }
            requestTask = uni.request({
                'url': opt.url,
                'method': opt.method,
                'data': opt.data,
                'header': opt.header,
                'dataType': opt.dataType || 'JSON',
                'timeout': opt.timeout,
                // #ifdef H5
                'withCredentials': true,
                // #endif
                // responseType:opt.responseType,
                success(result) {
                    http.afterHttp(result).then(res => {
                        if (opt.header.loading.show) { uni.hideLoading(); }
                        resolve(res);
                    }).catch(err => {
                        uni.showToast({
                            'icon': 'none',
                            'duration': 2000,
                            'title': err || '请求失败'
                        });
                        reject(err);
                    });
                },
                fail(err) {
                    console.log(21);
                    uni.showToast({
                        'icon': 'none',
                        'duration': 2000,
                        'title': err || '请求失败'
                    });
                    reject(err);
                },
                complete(res) {
                    if (requestTask) {
                        requestTask.abort();
                    }
                    if (opt.header.loading.show) { uni.hideLoading(); }
                }
            });
        }).catch(err => {
            console.log(31);
            uni.showToast({
                'icon': 'none',
                'duration': 2000,
                'title': err || '请求失败'
            });
            reject(err);
        });
    });
};


http.beforeHttp = config => {
    return new Promise((resolve, reject) => {
        const page = $utils.getCurPage().route;
        // const userInfo = JSON.parse(uni.getStorageSync('userInfo') || '{}') || {};
        const { access_token, user_code, user_name } = store.state.userInfo || {};
        config.header = Object.assign({
            'content-type': 'application/json; charset=UTF-8'
        }, config.header);
        config.data = {
            access_token,
            user_code,
            user_name,
            ...Object.assign(config.data)
        };
        if (whitePages.includes(page)) {
            resolve(config);
        } else if (access_token) {
            resolve(config);
        } else {
            reject('登录失效，请重新登录');
            store.commit('commitClear');
            uni.reLaunch({
                'url': '/pages/login/index'
            });
        }
    });
};
http.afterHttp = res => {
    return new Promise((resolve, reject) => {
        const httpSuccess = res.data && (Number(res.statusCode) >= 200 && Number(res.statusCode) < 400);
        if (httpSuccess) {
            let rs = {};
            // #ifndef H5
            rs = res.data ? JSON.parse(res.data) : {};
            // #endif
            // #ifdef H5
            rs = res.data ? res.data : {};
            // #endif
            if (rs.returnCode === 0) {
                resolve(rs);
            }
            reject(rs.data);
        }
        uni.showLoading({
            'title': '请求失败，请稍后再试',
            'mask': true
        });
        reject(res?.data);
    });
};


http.install = Vue => {
    Vue.mixin(mainMixin);
    Vue.prototype.$utils = $utils;
};


export default http;
